package com.spark.core;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.spark.actions.BaseAction;
import com.spark.dao.SessionFactory;
import com.spark.util.MemcachedHelper;

@SuppressWarnings("unchecked")
public class SparkDataService extends SparkServlet {

	private static final long serialVersionUID = 1439184998611090718L;

	/**
	 * (1) query 
	 * (2) execute 
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = null;
		try {
			initRequestAndResponse(request, response);
			response.setContentType(SparkConfiguration.CONTENT_TYPE_JSON);
			out = response.getWriter();
			String suk = request.getParameter(SparkContext.SPARK_USER_KEY);			
			if(suk == null || MemcachedHelper.get(suk) == null){
				Message message = new Message(false);
				message.sessionTimeOut();
				JacksonMapper.getInstance().writeValue(out, message);
				return;
			}
			
			SparkContext context =  new SparkContext(SparkConfiguration.getInstance());
			initContext(context,request,response);
			String path = getServicePath(request);
			Message message = new Message(true);
			if (path != null) {
				String[] args = path.split("/");
				String statement = args[1];
				String action = args[2];
				if (BaseAction.ACTION_QUERY.equalsIgnoreCase(action)) {
					doQuery(context, statement, message);
				} else if (BaseAction.ACTION_EXECUTE.equalsIgnoreCase(action)) {
					doExecute(context, statement, message);
				}else if (BaseAction.ACTION_DELETE.equalsIgnoreCase(action)) {
					doDelete(context, statement, message);
				}
			}
			
			JacksonMapper.getInstance().writeValue(out, message);
		} catch (Exception e) {
			// TODO:处理异常机制
			e.printStackTrace();
			Message message = new Message(false);
			message.setError("系统发生一个错误,请联系系统管理员!错误号:xxxx");
			out = response.getWriter();
			JacksonMapper.getInstance().writeValue(out, message);
		} finally {
			if (out != null) out.close();
		}
	}
	
	
	private void doQuery(SparkContext context, String statement, Message message) throws Exception {
		Map params = context.getParameterMap();
		XMap request = context.getParameter();
		Integer pageSize = request.getInt(BaseAction.QUERY_PAGE_SIZE);
		SqlSession sqlSession = SessionFactory.getSession();
		try {
			if (-1!=pageSize) {
				BaseAction.parsePageSizeAndPageNum(context, params);
				Integer total = (Integer) sqlSession.selectOne(statement.concat(BaseAction.STATMENT_COUNT), params);
				message.put(BaseAction.TOTAL, total);
			}
			List list = sqlSession.selectList(statement, params);
			message.setResult(list);
		} finally {
			SessionFactory.closeSession(sqlSession);
		}
	}
	
	
	private void doDelete(SparkContext context, String statement, Message message) throws Exception {
		List list = context.getParameterList();
		if(list.size() > 0) {
			SqlSession sqlSession = SessionFactory.getSession(false);
			try {
				Iterator it = list.iterator();
				while(it.hasNext()){
					Map item = (Map)it.next();
					//TODO:改进一下
					item.putAll(context.getSession());
					sqlSession.delete(statement, item);
				}
				sqlSession.commit();
				message.setResult(list);
			} finally {
				SessionFactory.closeSession(sqlSession);
			}
		}
	}
	
	
	private void doExecute(SparkContext context, String statement, Message message) throws Exception {
		
	}

}
